package cn.service.Impl;

import cn.dao.ApproveInfoDao;
import cn.dao.FlowDao;
import cn.dao.TemplateDao;
import cn.domain.*;
import cn.service.FlowService;
import cn.utils.HQLHelper;
import org.apache.struts2.ServletActionContext;
import org.jbpm.api.ProcessEngine;
import org.jbpm.api.ProcessInstance;
import org.jbpm.api.ProcessInstanceQuery;
import org.jbpm.api.TaskQuery;
import org.jbpm.api.task.Task;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.management.Query;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/4/26.
 */
@Service
@Transactional
public class FlowServiceImpl implements FlowService {
    @Resource
    private FlowDao flowDao;

    @Resource
    private ProcessEngine processEngine;

    @Resource
    private ApproveInfoDao approveInfoDao;

    @Override
    public void save(Application application) {
        //保存
        flowDao.save(application);
        //设置流程变量
        Map<String,Application> map=new HashMap<String,Application>();
        map.put("application",application);
        //获取key值
        Template template = application.getTemplate();
        String key = template.getProcessDefinitionKey();         //获取key值
        //启动流程实例
        ProcessInstance processInstance= processEngine.getExecutionService().startProcessInstanceByKey(key,map);

        //获取任务id
        TaskQuery query=processEngine.getTaskService().createTaskQuery();
        //获取当前流程定义下的实例
        query.processInstanceId(processInstance.getId());
        Task task=query.uniqueResult();

        //办理任务
        processEngine.getTaskService().completeTask(task.getId());
    }

    /**
     * 分页信息
     * @param hqlHelper
     * @param currentPage
     * @return
     */
    @Override
    public PageBean getPageBean(HQLHelper hqlHelper, int currentPage) {
        return flowDao.getPageBean(hqlHelper,currentPage);
    }
    /**
     * 根据模板id获取此模板对应的文件输入流
     * @param id
     * @return
     * public String downLoad() throws IOException {
    //根据id查询数据
    Template template=templateService.getById(model.getId());
    //查询需要下载的输入流
    downLoad=templateService.getInputStreamById(model.getId());
    //文件名
    fileName=template.getName()+".doc";
    String  agent=ServletActionContext.getRequest().getHeader("user-agent");
    fileName=encodeDownloadFilename(fileName,agent);
    return "downLoad";
     */
    @Override
    public InputStream getInputStreamById(Long id) {
        Application application=flowDao.getById(id);
        String path=application.getFilePath();
        InputStream in=null;
        try {
            in=new FileInputStream(new File(path));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return in;
    }

    @Override
    public Application getById(Long applicationId) {
        return flowDao.getById(applicationId);
    }

    @Override
    public List<TaskView> findTaskList(User currentUser) {
        //根据用户查询当前任务
        List<Task> taskList=processEngine.getTaskService().findPersonalTasks(currentUser.getName());
        List<TaskView> taskViews=new ArrayList<TaskView>();
        for (Task task:taskList){
            Application application= (Application) processEngine.getTaskService().getVariable(task.getId(),"application");
            TaskView tv=new TaskView(task,application);
            taskViews.add(tv);
        }
        return taskViews;
    }

    @Override
    public void approve(ApproveInfo approveInfo, String taskId) {
        //根据任务Id查询任务
        Task task=processEngine.getTaskService().getTask(taskId);
        String execuTionId=task.getExecutionId();//获得执行Id

        //保存
        approveInfoDao.save(approveInfo);
        //办理任务
        processEngine.getTaskService().completeTask(taskId);
        ProcessInstanceQuery query=processEngine.getExecutionService().createProcessInstanceQuery();
        query.processInstanceId(execuTionId);//添加过滤条件
        ProcessInstance processInstance=query.uniqueResult();

        if(approveInfo.getApproval()){
            //审批通过
            if(processInstance==null){
                //当前办理是最后一个任务
                approveInfo.getApplicaTion().setStatus(Application.STATUS_APPROVED);
            }
        }else{
            //审批不通过
            if(processInstance!=null){
                //流程未结束，手动结束当前实例
                processEngine.getExecutionService().endProcessInstance(execuTionId,ProcessInstance.STATE_ENDED);
                approveInfo.getApplicaTion().setStatus(Application.STATUS_UNAPPROVED);
            }
        }

    }
}
